package com.jastar.android.game.richman.logic.handler;

import com.jastar.android.game.richman.GameActivity;
import com.jastar.android.game.richman.logic.bean.Cell;
import com.jastar.android.game.richman.logic.bean.Player;
import com.jastar.android.game.richman.logic.card.Card;
import com.jastar.android.game.richman.logic.card.EarthquakeCard;
import com.jastar.android.game.richman.logic.card.LevelupCard;
import com.jastar.android.game.richman.logic.card.StepCard;
import com.jastar.android.game.richman.logic.enums.CellType;
import com.jastar.android.game.richman.logic.weight.WeightSet;
import com.jastar.android.util.Alert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class CellShopHandler extends CellDefaultHandler {
    private static final int OPTION_NUM = 2;
    private static final int MAX_CARDS = 3;
    private final WeightSet<Card> cards;

    public CellShopHandler() {
        List<Card> list = new ArrayList<>();
        list.add(new StepCard("步行卡：可以指定行走步数", 6, 1));
        list.add(new LevelupCard("升级卡(1级)：随机升级1处你的房产", 4, 1, 1));
        list.add(new LevelupCard("升级卡(2级)：随机升级2处你的房产", 2, 2, 2));
        list.add(new LevelupCard("升级卡(3级)：随机升级3处你的房产", 1, 3, 3));
        list.add(new EarthquakeCard("暴雨卡：随机摧毁2处房产(包含自己)", 2, 1, 2));
        list.add(new EarthquakeCard("地震卡：随机摧毁3处房产(包含自己)", 1, 2, 3));
        cards = new WeightSet<>(list);
    }

    @Override
    public void hand(GameActivity activity, Cell cell, Player p, CellType.Callback callback) {
        Card[] options = new Card[OPTION_NUM];
        IntStream.range(0, OPTION_NUM).forEach(i -> options[i] = cards.random());
        String[] texts = Stream.concat(Arrays.stream(options).map(Card::getMessageWithPrice), Stream.of("不购买"))
                .toArray(String[]::new);
        Alert.select(activity, p.getIcon(), "请选择要购买的卡片：", (d, w) -> {
            if (w < options.length) {
                Card card = options[w];
                if (!(p.getCards().size() < MAX_CARDS)) {
                    Alert.info(activity, p.getIcon(), "购买失败，最多" + MAX_CARDS + "张卡片.", (d1, w1) -> callback.callback());
                } else if (p.getMoney() < card.getPrice()) {
                    Alert.info(activity, p.getIcon(), "购买失败，现金不足.", (d1, w1) -> callback.callback());
                } else {
                    p.addCard(card);
                    p.pay(card.getPrice());
                    callback.callback();
                }
            }
        }, texts);
    }

}
